package com.yonyou.ucf.mdf.app.controller;

import com.yonyou.ucf.mdd.common.model.uimeta.FilterSolution;
import com.yonyou.ucf.mdd.common.model.uimeta.FilterSolutionCommon;
import com.yonyou.ucf.mdd.common.model.uimeta.MetaFilterItem;
import com.yonyou.ucf.mdd.common.model.uimeta.MetaFilters;
import com.yonyou.ucf.mdd.common.model.uimeta.filter.vo.FilterVO;
import com.yonyou.ucf.mdd.common.model.uimeta.filter.vo.SolutionSaveVO;
import com.yonyou.ucf.mdd.common.model.uimeta.filter.vo.SolutionVO;
import com.yonyou.ucf.mdd.ext.base.BaseController;
import com.yonyou.ucf.mdd.ext.base.user.User;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.filter.converter.SolutionConvert;
import com.yonyou.ucf.mdd.ext.filter.service.IFilterService;
import com.yonyou.ucf.mdd.ext.i18n.utils.MddMultilingualUtil;
import com.yonyou.ucf.mdd.ext.pb.bill.MetaFilterItemExt;
import com.yonyou.ucf.mdd.ext.util.Logger;
import com.yonyou.ucf.mdd.ext.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.imeta.biz.base.BizException;
import org.imeta.spring.support.db.OrmException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 过滤设计Controller
 *
 * @author wufeng
 */
@Slf4j
@RestController
@RequestMapping("/filterDesign")
public class FilterDesignController extends BaseController {

    @Autowired
    private IFilterService filterService;

    @Autowired
    private ApplicationContext applicationContext;

    public IFilterService getFilterService() {
        return filterService;
    }

    public void setFilterService(IFilterService filterService) {
        this.filterService = filterService;
    }

    /**
     * 保存过滤方案
     * 前台文兵用的时候，快捷保存过滤方案，应该把commonVOs的isCommon设置成1
     *
     * @param
     * @param request
     * @param response
     */
    public void addSolution1(@RequestBody SolutionSaveVO solutionSaveVO, HttpServletRequest request, HttpServletResponse response) {
        FilterVO filterVO = solutionSaveVO.getFilterVO();
        SolutionVO solutionVO = solutionSaveVO.getSolutionVO();
        if (null != solutionVO) {
            //赋值方案所属用户
            solutionVO.setUserId(getUserId(request));
        }
        try {
            FilterSolution solution = filterService.insertSolutionAll2(solutionVO, filterVO);
            renderJson(response, ResultMessage.data(solution));
        } catch (Exception e) {
            Logger.error("[addSolution1] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    private Object getUserId(HttpServletRequest request) {
        User user = AppContext.getCurrentUser(request.getParameter("token"));
        Object userId = AppContext.getUserId();
        return userId;
    }

    /**
     * 保存过滤方案
     * 前台文兵用的时候，快捷保存过滤方案，应该把commonVOs的isCommon设置成1
     *
     * @param
     * @param request
     * @param response
     */
    @RequestMapping("/addSolutionAll")
    public void addSolutionAll(@RequestBody SolutionSaveVO solutionSaveVO, HttpServletRequest request, HttpServletResponse response) {
        FilterVO filterVO = solutionSaveVO.getFilterVO();
        SolutionVO solutionVO = solutionSaveVO.getSolutionVO();
        if (null != solutionVO) {
            //赋值方案所属用户
            solutionVO.setUserId(getUserId(request));
        }
        try {
            FilterSolution solution = filterService.insertSolutionAll2(solutionVO, filterVO);
            renderJson(response, ResultMessage.data(solution));
        } catch (Exception e) {
            Logger.error("[addSolutionAll] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 更新过滤方案，文兵快捷的修改调用，将过滤总信息和内容一起传回来
     *
     * @param solutionSaveVO
     * @param request
     * @param response
     */
    @RequestMapping("/updateSolutionAll")
    public void updateSolutionAll(@RequestBody SolutionSaveVO solutionSaveVO, HttpServletRequest request, HttpServletResponse response) {
        FilterVO filterVO = solutionSaveVO.getFilterVO();
        SolutionVO solutionVO = solutionSaveVO.getSolutionVO();
        try {
            renderJson(response, ResultMessage.data(filterService.updateSolutionAll(solutionVO, filterVO)));
        } catch (Exception e) {
            Logger.error("[updateSolutionAll] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 更新过滤方案（总方案信息）
     *
     * @param
     * @param request
     * @param response
     */
    @RequestMapping("/updateSolution")
    public void updateSolution(@RequestBody FilterSolution vo, HttpServletRequest request, HttpServletResponse response) {
//		FilterSolution vo = new Gson().fromJson(json, FilterSolution.class);
        try {
            filterService.updateSolution(vo);
            renderJson(response, ResultMessage.data(MddMultilingualUtil.getFWMessage("P_YS_FW-PUB_MDD-BACK_0001065267", "更新成功！")));
        } catch (Exception e) {
            Logger.error("[updateSolution] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 更新常用过滤方案
     *
     * @param
     * @param request
     * @param response
     */
    @RequestMapping("/updateSolutionCommon")
    public void updateSolutionCommon(@RequestBody FilterSolutionCommon[] commons, HttpServletRequest request, HttpServletResponse response) {
        try {
            filterService.updateSolutionCommonItem(commons);
            renderJson(response, ResultMessage.data(MddMultilingualUtil.getFWMessage("P_YS_FW-PUB_MDD-BACK_0001065173", "更新成功")));
        } catch (Exception e) {
            Logger.error("[updateSolutionCommon] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 获取过滤方案列表
     *
     * @param
     * @param request
     * @param response
     */
    @RequestMapping("/getSolutionList")
    public void getSolutionList(@RequestBody Map<String, String> paramMap, HttpServletRequest request, HttpServletResponse response) {
        if (null == paramMap || null == paramMap.get("filterId")) {
            renderJson(response, ResultMessage.error(MddMultilingualUtil.getFWMessage("P_YS_FW-PUB_MDD-BACK_0001065379", "过滤id为空！")));
        } else {
            long filterId = Long.valueOf(paramMap.get("filterId"));
            String domain = paramMap.get("domain");
            String terminalType = request.getParameter("terminalType");
            try {
                List<FilterSolution> list = filterService.solutionsListWithUserId(null, filterId, terminalType, domain);
                renderJson(response, ResultMessage.data(list, true));
            } catch (Exception e) {
                Logger.error("[getSolutionList] 异常", e);
                renderJson(response, ResultMessage.error(e.getMessage()));
            }
        }
    }

    /**
     * 获取常用方案列表
     *
     * @param
     * @param request
     * @param response
     */
    @RequestMapping("/getSolutionCommonList")
    public void getSolutionCommonList(@RequestBody HashMap<String, Long> paramMap, HttpServletRequest request, HttpServletResponse response) {
        long solutionId = paramMap.get("solutionId");
        try {
            List<FilterSolutionCommon> list = filterService.getSolutionCommonList(solutionId);
            renderJson(response, ResultMessage.data(list, true));
        } catch (Exception e) {
            Logger.error("[getSolutionCommonList] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * loadDefaultSolution == 1 走三合一接口
     *
     * @param domain
     * @param filterId
     * @param request
     * @param response
     */
    @RequestMapping("/getFilterBase")
    public void getFilterBase(@RequestParam(required = false) String domain, long filterId, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (StringUtils.isNotEmpty(domain) && domain.equalsIgnoreCase(applicationContext.getId())) {
                domain = null;
            }
            String loadDefaultSolution = request.getParameter("loadDefaultSolution");
            if ("1".equals(loadDefaultSolution)) {
                loadDefaultSolution(domain, filterId, request, response);
                return;
            }
            MetaFilters filter = filterService.metaFilters(filterId, domain);
            renderJson(response, ResultMessage.data(filter));
        } catch (Exception e) {
            Logger.error("[getFilterBase] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 删除过滤方案
     *
     * @param request
     * @param response
     */
    @RequestMapping("/delSolution")
    public void delSolution(@RequestParam(required = false) String domain, @RequestParam long solutionId, HttpServletRequest request, HttpServletResponse response) {
        try {
            filterService.deleteSolution(solutionId, domain);
            renderJson(response, ResultMessage.success());
        } catch (Exception e) {
            Logger.error("[delSolution] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }


    /**
     * 过滤方案设置默认
     *
     * @param request
     * @param response
     * @author limy
     */
    @RequestMapping("/setDefaultFilter")
    public void setDefaultFilter(@RequestParam long solutionId, @RequestParam int isPublic, Integer terminalType, HttpServletRequest request, HttpServletResponse response) {
        try {
            filterService.setDefaultFilter(solutionId, isPublic, terminalType);
            renderJson(response, ResultMessage.success());
        } catch (Exception e) {
            Logger.error("[setDefaultFilter] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 过滤方案的保存
     *
     * @param request
     * @param response
     * @author limy
     */
    @RequestMapping("/saveSolution")
    public void saveSolution(@RequestBody Map<String, Object> solution, HttpServletRequest request, HttpServletResponse response) {
        try {
            String domain = (String) solution.get("domain");
            if (StringUtils.isNotEmpty(domain) && domain.equalsIgnoreCase(applicationContext.getId())) {
                solution.remove("domain");
            }
            String terminalType = request.getParameter("terminalType");
          /*  Cookie[] cookies = ParamUtils.escapeForObject(request.getCookies());
            String yhtAccessToken = "";
            for (Cookie cookie : cookies) {
                if ("yht_access_token".equals(cookie.getName())) {
                    yhtAccessToken = cookie.getValue();
                    break;
                }
            }
            LoginUser currentUser = AppContext.getCurrentUser();
            currentUser.setYhtAccessToken(yhtAccessToken);
            AppContext.setCurrentUser(currentUser);*/
            if (null == terminalType) {
                terminalType = "1";
            }
            solution.put("terminalType", terminalType);
            filterService.saveSolution(solution);
            renderJson(response, ResultMessage.success());
        } catch (Exception e) {
            Logger.error("[saveSolution] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 获取过滤栏目信息
     *
     * @param filtersId
     * @param request
     * @param response
     */
    @RequestMapping("/getFiltersInfo")
    public void getFiltersInfo(@RequestParam(required = false) String domain, @RequestParam Long filtersId, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<MetaFilterItem> list = filterService.filtersInfoList(filtersId, domain);
            renderJson(response, ResultMessage.data(list));
        } catch (Exception e) {
            Logger.error("[saveSolution] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 查询方案三合一接口
     *
     * @param domain
     * @param filterId
     * @param request
     * @param response
     */
    @RequestMapping("/loadDefaultSolution")
    public void loadDefaultSolution(@RequestParam(required = false) String domain, long filterId, HttpServletRequest request, HttpServletResponse response) {
        try {
            String terminalType = request.getParameter("terminalType");
            String viewid = request.getParameter("viewid");
            String loadDefaultSolution = request.getParameter("loadDefaultSolution");
            // 获取solution
            List<Object> resultList = filterService.loadDefaultSolution(filterId, terminalType, viewid, domain);
            try {
                if ("1".equals(loadDefaultSolution)) {
                    Map<String, Object> resultData = new HashMap<>();
                    resultData.put("data", resultList);
                    resultData.put("loadDefaultSolution", 1);
                    //设置返回版本号
//                    resultData.put("mddVersion", "304");
                    renderJson(response, ResultMessage.data(resultData));
                } else {
                    renderJson(response, ResultMessage.data(resultList));
                }
            } catch (Exception e) {
                Logger.error("[loadDefaultSolution] 异常", e);
                renderJson(response, ResultMessage.data(resultList));
            }
        } catch (Exception e) {
            Logger.error("[loadDefaultSolution] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    @RequestMapping(value = "/{solutionId}/solutionFilters", method = RequestMethod.GET)
    public void getAllCommonFilters(@PathVariable long solutionId, HttpServletRequest request, HttpServletResponse response) {
        try {
            Object userid = AppContext.getUserId();
            String viewid = request.getParameter("viewid");
            String domain = request.getParameter("domain");
            SolutionConvert convert = new SolutionConvert(this.filterService, solutionId, userid, viewid, domain);
            renderJson(response, ResultMessage.data(convert.getSolutionFilters(true)));
        } catch (BizException | OrmException e) {
            Logger.error("[getAllCommonFilters] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        } catch (Exception e) {
            Logger.error("getAllCommonFilters", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }
    //=======自定义的过滤项========

    /**
     * todo  测试无数据，需要验证
     * 获取客户自定义过滤栏目
     *
     * @param filtersId
     * @param request
     * @param response
     */
    @RequestMapping("getCustMetaFilterItems")
    public void getCustMetaFilterItems(@RequestParam long filtersId, @RequestParam(required = false) String domain, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<MetaFilterItemExt> list = filterService.getCustMetaFilterItems(filtersId, domain);
            renderJson(response, ResultMessage.data(list));
        } catch (Exception e) {
            Logger.error("[getCustMetaFilterItems] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 获取自定义栏目通过栏目ID
     *
     * @param itemId
     * @param request
     * @param response
     */
    @RequestMapping("getCustMetaFilterItemById")
    public void getCustMetaFilterItemById(@RequestParam Long itemId, @RequestParam(required = false) String domain, HttpServletRequest request, HttpServletResponse response) {
        try {
            MetaFilterItemExt filterItemExt = filterService.getCustMetaFilterItemById(itemId, domain);
            renderJson(response, ResultMessage.data(filterItemExt));
        } catch (Exception e) {
            Logger.error("[getCustMetaFilterItemById] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 保存自定义过滤栏目
     *
     * @param request
     * @param response
     */
    @RequestMapping("saveCustMetaFilterItem")
    public void saveCustMetaFilterItem(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        try {
            //在列表中和不再列表中默认设置成多选
            if ("in".equals((String) map.get("compareLogic")) || "nin".equals((String) map.get("compareLogic"))) {
                map.put("multSelect", 1);
            }
            filterService.saveCustMetaFilterItem(map);
            renderJson(response, ResultMessage.success());
        } catch (Exception e) {
            Logger.error("[saveCustMetaFilterItem] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 删除自定义项过滤栏目
     *
     * @param itemId
     * @param request
     * @param response
     */
    @RequestMapping("delCustMetaFilterItem")
    public void delCustMetaFilterItem(@RequestParam Long itemId, @RequestParam(required = false) String domain, HttpServletRequest request, HttpServletResponse response) {
        try {
            filterService.delCustMetaFilterItem(itemId, domain);
            renderJson(response, ResultMessage.success());
        } catch (Exception e) {
            Logger.error("[delCustMetaFilterItem] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 校验表达式
     *
     * @param params
     * @param request
     * @param response
     */
    @RequestMapping("checkCondition")
    public void checkCondition(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        try {
            String expression = filterService.checkCondition(params);
            renderJson(response, ResultMessage.data(expression));
        } catch (Exception e) {
            Logger.error("[checkCondtion] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    /**
     * 目前暂时按照非统一存储来实现，需求后续讨论
     *
     * @param request
     * @param response
     */
    @RequestMapping("getEnumList")
    public void getEnumList(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String, String>> enumList = filterService.getEnumList();
            renderJson(response, ResultMessage.data(enumList));
        } catch (Exception e) {
            Logger.error("[getEnumList] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    @RequestMapping("getRefList")
    public void getRefList(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String, String>> enumList = filterService.getRefList();
            renderJson(response, ResultMessage.data(enumList));
        } catch (Exception e) {
            Logger.error("[getRefList] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }

    @RequestMapping("getRefRetList")
    public void getRefRetList(@RequestParam String refCode, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String, String>> enumList = filterService.getRefRetList(refCode);
            renderJson(response, ResultMessage.data(enumList));
        } catch (Exception e) {
            Logger.error("[getRefList] 异常", e);
            renderJson(response, ResultMessage.error(e.getMessage()));
        }
    }


}
